from django.shortcuts import render_to_response
from Person.models import  Person
from Person.models import  PersonForm
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.template import RequestContext

def index(request):
    people = Person.objects.all().order_by('-birthDate')
    paginator = Paginator(people, 111)

    try: page = int(request.GET.get("page", '1'))
    except ValueError: page = 1

    try:
        people = paginator.page(page)
    except (InvalidPage, EmptyPage):
        people = paginator.page(paginator.num_pages)


    return render_to_response('Person/index.html', {'people': people})


def detail(request, idno):
    person = Person.objects.get(id_no = idno)

    form =  PersonForm(request.POST, instance=person )

    return render_to_response('Person/details.html', {'form': form, 'person': person})


def edit(request, idno):
    person = Person.objects.get(id_no = idno)

    form =  PersonForm(instance=person )
    c = {}
    c.update(csrf(request))
    return render_to_response('Person/edit.html', {'person': form, 'org': person},context_instance=RequestContext(request) )


def validate(request, idno):
    if request.method == 'POST': # If the form has been submitted...
        person = Person.objects.get(id_no = idno)
        form = PersonForm(request.POST, instance=person) # A form bound to the POST data
        if form.is_valid:

            form.save(commit = True);
            return HttpResponseRedirect('../details/') # Redirect after POST
    else:
        person = Person.objects.get(id_no = idno)

        form =  PersonForm(instance=person )

        return render_to_response('Person/edit.html', {'person': form, 'org': person})


